'use strict';

let API_VERSION;
let BASE_URL;
let WS_BASE_URL;


window.onload = function () {
    API_VERSION = "/ccu/api/v1";
    if (location.protocol === "https:") {
        BASE_URL = "https://" + location.host + API_VERSION;
        WS_BASE_URL = "wss://" + location.host + API_VERSION;
    } else {
        BASE_URL = "http://" + location.host + API_VERSION;
        WS_BASE_URL = "ws://" + location.host + API_VERSION;
    }

    if (ws == null) {
        ws = newWebsocket();
    }
}

let btnCall = document.getElementById('btnCall')
let ws = null;
btnCall.onclick = function() {
    call();
}

// 创建websocket连接
function newWebsocket() {
    let webSocket = new WebSocket(WS_BASE_URL + "/device/ws")
    webSocket.addEventListener('open', function () {
        console.log("ws open")
        start();
    })
    webSocket.addEventListener('close', function () {
        console.log("ws close")
    })
    webSocket.addEventListener('error', function () {
        console.log("ws error")
    })
    webSocket.addEventListener('message', function (evt) {
        console.log(evt.data)
        on_websocket_message(evt)
    })

    return webSocket
}

// 处理websocket消息
function on_websocket_message(evt) {
    ws_onmessage(evt)
}


function appPost(url, param, success) {
    url = BASE_URL + url
    $.ajax({
        url: url, // 目标资源
        cache: false, //true 如果当前请求有缓存的话，直接使用缓存。如果该属性设置为 false，则每次都会向服务器请求
        //async: false, //默认是true，即为异步方式
        data: JSON.stringify(param),
        dataType: "json", // 服务器响应的数据类型
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", token);
        },
        type: "POST", // 请求方式
        success: success,
        error: function (r, error, exp) {
            console.log(r, error, exp)
        }
    });
}

function appGet(url, success) {
    url = BASE_URL + url
    $.ajax({
        url: url, // 目标资源
        cache: false, //true 如果当前请求有缓存的话，直接使用缓存。如果该属性设置为 false，则每次都会向服务器请求
        //async: false, //默认是true，即为异步方式
        type: "GET", // 请求方式
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", token);
        },
        success: success,
        error: function (r, error, exp) {
            console.log(r, error, exp)
        }
    });
}
